//
//  AudioPlayer.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/4.
//

import AVFoundation

class AudioPlayer: ObservableObject {
    var player: AVAudioPlayer?
    var player2: AVAudioPlayer?
    
    init() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("Failed to set up audio session: \(error.localizedDescription)")
        }
    }
    
    func playSound(file: String, type: String = "mp3", isDefaultPlayer: Bool = true) {
        guard let url = Bundle.main.url(forResource: file, withExtension: type) else {
            print("Sound file not found")
            return
        }
        
        do {
            if isDefaultPlayer {
                player = try AVAudioPlayer(contentsOf: url)
                player?.play()
            } else {
                player2 = try AVAudioPlayer(contentsOf: url)
                player2?.play()
            }
        } catch {
            print("Error loading sound file: \(error.localizedDescription)")
        }
    }
    
    func playSoundLoop(file: String, type: String = "mp3", isDefaultPlayer: Bool = true) {
        guard let url = Bundle.main.url(forResource: file, withExtension: type) else {
            print("Sound file not found")
            return
        }
        
        do {
            if isDefaultPlayer {
                player = try AVAudioPlayer(contentsOf: url)
                player?.numberOfLoops = -1 // 无限循环播放
                player?.play()
            } else {
                // 同时播放时，调小默认播放器音量
                player?.volume = 0.5
                player2 = try AVAudioPlayer(contentsOf: url)
                player2?.volume = 1.0
                player2?.numberOfLoops = -1 // 无限循环播放
                player2?.play()
            }
        } catch {
            print("Error loading sound file: \(error.localizedDescription)")
        }
    }
    
    func stopSound(isDefaultPlayer: Bool = true) {
        if isDefaultPlayer {
            player?.stop()
            player = nil
        } else {
            // 关闭辅助音时，调大默认播放器音量
            player?.volume = 1.0
            player2?.stop()
            player2 = nil
        }
    }
    
    func pauseSound(isDefaultPlayer: Bool = true) {
        if isDefaultPlayer {
            player?.pause()
        } else {
            player2?.pause()
        }
    }
}
